import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Message, Box, Icon, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { column } from './stores/definitions';
import { useHistory, useParams } from 'react-router';
import SelfShiftSet from './components/SelfShiftSet';
import ShiftTimeForm from './components/ShiftTimeForm';
import moment from 'moment';


const tabItems = [
  { key: '0', label: t`未执行自营班次` },
  { key: '1', label: t`历史自营班次` },
];

function ScSelfPrice() {
  const [lineInfo, setLineInfo] = useState();
  const { scSelfStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const curRef = useRef(); // table中的选中行
  const history = useHistory();
  const { id } = useParams();

  useEffect(() => {
    (async () => {
      await init();
    })();
    return (() => {
      store.data = [];
      store._action = '0';
    });
  }, [store.search]);

  async function init() {
    const res = await store.getPriceInfo(id);
    setLineInfo(res);
  }

  const handleSearch = (params) => {
    const { orderDate, ...searchArgs } = params.values;
    const [from, to] = orderDate || [];
    store.search = {
      findTypes: [1],
      from,
      to,
      routePriceId: id,
      ...searchArgs,
    };
  };

  // 点击打开添加拼车班次
  const handleOpenAdd = () => {
    curRef.current = {};
    setModal(['add']);
  };

  // 新增订单数据提交
  const handleCreate = async (price, isCreate) => {
    const content = isCreate ? t`创建` : t`更新`;
    if (!_.isEmpty(price)) {
      try {
        Dialog.confirm({
          title: t`是否即刻生效`,
          okProps: {
            children: '是', // 设置确定按钮的文本
          },
          cancelProps: {
            children: '否', // 设置取消按钮的文本
          },
          onOk: async () => {
            try {
              if (isCreate) {
                await store.create(toJS(price), '1');
              } else {
                await store.updateRsShift(toJS(price), '1');
              }
              Message.success({ content: `${content}${t`成功`}`, duration: 7000 });
            } catch (error) {
              Message.error({ content: `${content}${t`失败`}`, duration: 7000 });
            }
            setModal([]);
          },
          onCancel: async () => {
            try {
              if (isCreate) {
                await store.create(toJS(price), '2');
              } else {
                await store.updateRsShift(toJS(price), '2');
              }
              Message.success({ content: `${content}${t`成功`}`, duration: 7000 });
            } catch (error) {
              Message.error({ content: `${content}${t`失败`}`, duration: 7000 });
            }
            setModal([]);
          },
        });
      } catch (e) {
        Message.error({ content: `${content}${t`失败`}`, duration: 7000 });
        throw e;
      }
    }
  };

  const handleDelete = (shiftId) => {
    Dialog.confirm({
      content: t`确认删除该线路吗？`,
      onOk: async () => {
        try {
          await store.remove(toJS(shiftId));
          Message.success({ content: t`删除成功` });
        } catch (e) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw e;
        }
      },
    });
  };

  // 编辑自营班次出发时间
  const handleEditShiftsTime = async (result) => {
    curRef.current = result;
    setModal(['edit']);
    // try {
    //   const { shiftDate, shiftTime } = result;
    //   const assembleTime = `${shiftDate} ${shiftTime}`;
    //   const { id: priceId } = lineInfo;
    //   const res = await store.existRsOrder({ shiftTime: moment(assembleTime, 'YYYY-MM-DD HH:mm').toISOString(), priceId });
    //   if (res) {
    //     Dialog.confirm({
    //       title: t`警告`,
    //       content: t`当前班次下存在订单, 是否继续编辑班次时间`,
    //       onOk: () => {
    //         curRef.current = result;
    //         setModal(['edit']);
    //       },
    //     });
    //   } else {
    //     curRef.current = result;
    //     setModal(['edit']);
    //   }
    // } catch (error) {
    //   Message.error({ content: t`查询失败`, duration: 7000 });
    //   throw error;
    // }
  };

  const handleUpdateShiftsTime = (result) => {
    Dialog.confirm({
      content: t`确认要更新该班次信息吗？`,
      onOk: async () => {
        try {
          await store.updateTime(toJS(result));
          Message.success({ content: t`更新成功` });
        } catch (e) {
          Message.error({ content: t`更新失败`, duration: 7000 });
          throw e;
        }
        setModal([]);
      },
    });
  };

  return (
    <TauPage className="page-container">
      <Box direction="row" align="center" margin={10}>
        <Button type="normal" onClick={() => { history.goBack(); }} style={{ marginLeft: '-10px', border: 0 }}>
          <Icon type="arrow-left" style={{ padding: 6, border: '1px solid #ccc', borderRadius: '50%', color: 'var(--btn-pure-primary-bg)' }} />
        </Button>
        <div>{t`专线线路【(${lineInfo?.beginAreaName}) ~ (${lineInfo?.endAreaName})】的自营班次信息`}</div>
      </Box>
      <TauActionPanel
        className="action-panel"
        onSearch={handleSearch}
        actions={[
          {
            name: 'btn-addPrice',
            title: t`自营班次生成`,
            type: 'primary',
            onClick: () => handleOpenAdd(),
          },
        ]}
        searchItems={[
          {
            name: 'shiftDate',
            type: 'datetime',
            props: {
              placeholder: t`发车日期`,
            },
          },
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`班次起始时间`, t`班次结束时间`],
            },
          },
        ]}
      />
      <div className="content">
        <Tab
          activeKey={store.action}
          onChange={(v) => {
            store.xcx = [];
            store.action = v;
          }}
        >
          {tabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
        <TauTable
          primaryKey="itemId"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('shiftCode', { width: 88 }),
            column('shiftDate', { width: 88 }),
            column('shiftTime', { width: 88 }),
            column('shiftType', { width: 88 }),
            column('price.RMB', { width: 88 }),
            column('company', {
              width: 88,
              cell: (_) => <span>{t`平台`}</span>,
            }),
            column('payEndTime', { width: 148 }),
            column('notGroupPayEndTime', { width: 148 }),
            column('enabled', { width: 88 }),
          ].concat(store._action === '0' ? [{
            title: t`操作`,
            dataIndex: 'id',
            width: 100,
            cell: (_, __, price) => (
              <>
                <Button text type="primary" onClick={() => handleEditShiftsTime(price)}>{t`编辑`}</Button>
                <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDelete(price?.id)} >{t`删除`}</Button>
              </>),
          }] : [])}
        />
      </div>
      <Drawer
        visible={modal[0] === 'add'}
        title={t`自营班次生成`}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        style={{ maxWidth: '65%' }}
        width="90%"
      >
        <SelfShiftSet
          modal={modal}
          onSubmit={handleCreate}
          onCancel={() => setModal([])}
          line={lineInfo}
          routePriceId={id}
          shiftData={toJS(store.data)}
        />
      </Drawer>
      <ShiftTimeForm
        modal={modal}
        visible={modal[0] === 'edit'}
        onSubmit={handleUpdateShiftsTime}
        onCancel={() => setModal([])}
        line={lineInfo}
        routePriceId={id}
        shiftsInfo={curRef.current}
        shiftData={toJS(store.data)}
      />
    </TauPage>
  );
}

export default observer(ScSelfPrice);
